package com.waimai_lp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.waimai_lp.common.BaseContext;
import com.waimai_lp.common.R;
import com.waimai_lp.entity.Orders;
import com.waimai_lp.entity.User;
import com.waimai_lp.service.UserService;
import com.waimai_lp.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();

        if(StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);

            //需要将生成的验证码保存到Session
            //session.setAttribute(phone,code);

            //将生成的验证码缓存到Redis中，并且设置有效期为5分钟
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);

            return R.success("手机验证码短信发送成功");
        }

        return R.error("短信发送失败");
    }

    /**
     * 发送邮箱验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsgEmail")
    public R<String> sendMsgEmail(@RequestBody User user, HttpSession session){
        //获取手机号
        String email = user.getEmail();
        String subject = "念思餐购登录验证码";

        if(StringUtils.isNotEmpty(email)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            String context = "欢迎使用念思餐购，登录验证码为: " + code + ",五分钟内有效，请妥善保管!";
            log.info("code={}",code);

            userService.sendMsg(email,subject,context);
            //将生成的验证码缓存到Redis中，并且设置有效期为5分钟
            redisTemplate.opsForValue().set(email,code,5,TimeUnit.MINUTES);

            return R.success("邮箱发送成功");
        }

        return R.error("邮箱发送失败");
    }


//    /**
//     * 获取用户信息*
//     * @param session
//     * @return
//     */
//    @PostMapping("getUserInfo")
//    public R<User> getInfo(HttpSession session){
//        Long id = (Long) session.getAttribute("user");
//        User user = userService.getById(id);
//        return R.success(user);
//    }

    /**
     * 获取用户信息*
     * @param
     * @return
     */
    @GetMapping("getUserInfo")
    public R<User> getInfo(){
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, BaseContext.getCurrentId());
        User user = userService.getOne(queryWrapper);
        if (user==null){
            return R.error("不存在用户");
        }
        return R.success(user);
    }

    /**
     * 手机端电话登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        //用户只能登录一次
        if (session.getAttribute("user")!=null){
                session.invalidate();
                return R.error("账户已登录!");
        }
        log.info(map.toString());
        //随机生成用户名
        int i;
        char []randName = new char[7];
        Random random = new Random();
        for (i=0;i<=6;i++){
            char ranLowLetter = (char) ((random.nextInt(26) + 97));
            randName[i]=ranLowLetter;
        }
        //转换为字符串
        String name=String.valueOf(randName);
        //获取手机号
        String phone = map.get("phone").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从Session中获取保存的验证码
        //Object codeInSession = session.getAttribute(phone);

        //从Redis中获取缓存的验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if(codeInSession != null && codeInSession.equals(code)){
            //如果能够比对成功，说明登录成功

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);


            User user = userService.getOne(queryWrapper);
            if(user == null){
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setName(name);
                user.setStatus(1);
                userService.save(user);
            }
//            session.setAttribute("userName",user.getName());
            session.setAttribute("user",user.getId());
//            String key="user_"+user.getId();
//            redisTemplate.opsForValue().set(key,user.toString(),30,TimeUnit.MINUTES);
            //如果用户登录成功，删除Redis中缓存的验证码
            redisTemplate.delete(phone);

            return R.success(user);
        }
        return R.error("登录失败");
    }

    /**
     * qq邮箱登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/loginEmail")
    public R<User> loginEmail(@RequestBody Map map, HttpSession session){
        log.info(map.toString());
//        //随机生成用户名
//        int i;
//        char []randName = new char[7];
//        Random random = new Random();
//        for (i=0;i<=6;i++){
//            char ranLowLetter = (char) ((random.nextInt(26) + 97));
//            randName[i]=ranLowLetter;
//        }
//        //转换为字符串
//        String name=String.valueOf(randName);
        //获取手机号
        String email = map.get("email").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从Session中获取保存的验证码
        //Object codeInSession = session.getAttribute(phone);

        //从Redis中获取缓存的验证码
        Object codeInSession = redisTemplate.opsForValue().get(email);

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if(codeInSession != null && codeInSession.equals(code)){
            //如果能够比对成功，说明登录成功

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail,email);


            User user = userService.getOne(queryWrapper);
            if(user == null){
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setEmail(email);
//                user.setName(name);
                user.setStatus(1);
                userService.save(user);
            }
//            session.setAttribute("userName",user.getName());
            session.setAttribute("user",user.getId());

            //如果用户登录成功，删除Redis中缓存的验证码
            redisTemplate.delete(email);

            return R.success(user);
        }
        return R.error("登录失败");
    }



    @PostMapping("/loginout")
    public R<String> out(HttpSession session){
        session.removeAttribute("user");
        return R.success("成功退出");
    }


    /**
     * * 获取用户
     * @return
     */
    @GetMapping("getCount")
    public R<Integer> getCount(){
        int count=0;
        List<User> list = userService.list();
        for (User user : list) {
            count++;
        }
        return R.success(count);
    }
}
